﻿using CommonTools;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;

namespace zhuaren
{
    class Program
    {
        static int i = 0;
        static List<people> peoples = new List<people>();
        static void Main(string[] args)
        {
            int i = 0;
            var top300 = GetTop300();
            if(top300.Count>0)
            {
                do
                {
                    var waits = new List<EventWaitHandle>();
                    for (var j = 0; j < 50 && i < top300.Count; j++)
                    {
                        var handler = new ManualResetEvent(false);
                        waits.Add(handler);
                        Thread t = new Thread(new ParameterizedThreadStart(Zhua));
                        t.Start(new Tuple<string, EventWaitHandle>(top300[i], handler));
                        i++;
                    }
                    WaitHandle.WaitAll(waits.ToArray());
                    Console.WriteLine(string.Format("已验证{0}个", i));
                } while (i < top300.Count);
            }
            File.WriteAllLines(Environment.CurrentDirectory+"\\rank.txt", peoples.OrderBy(x=>x.Rank).Select(x => x.ToString()));
            
        }
        static void Zhua(object o)
        {
            try
            {
                var locker=new object();
                var p = (Tuple<string, EventWaitHandle>)o;
                string i = p.Item1.Trim();

                var uri = "http://m.fangxinbao.com/wx/voteDetail-{0}.html";
                var file = Environment.CurrentDirectory + "\\people.txt";

                var result = HttpHelper.HttpGet(string.Format(uri, i), "", "text/html;charset=gb2312", encoding: "gbk");
                if (!string.IsNullOrWhiteSpace(result))
                {
                    var name = HttpHelper.GetNodeValue(result, "//div[contains(@class,'name-type')]");
                    var company = HttpHelper.GetNodeValue(result, "//div[contains(@class,'baoxian-type')]");
                    var rankinfo = HttpHelper.GetNodeValue(result, "//span[contains(@class,'cff5a1a')]");
                    var idnode = HttpHelper.GetNodeFormHtml(result, "//div[@id='pollbtn']");
                    var id = new Regex("(?<=').*(?=')").Match(idnode[0].Attributes["onclick"].Value).Value;
                    if (name.Length > 0 && company.Length > 0 && rankinfo.Length > 2)
                    {
                        var content = string.Format(@"{4}|{5}|{0}|{1}|{2}|{3}
", company[0], name[0], rankinfo[1], rankinfo[2],id,i);
                        peoples.Add(new people
                        {
                            id=int.Parse(id),
                            pageid=int.Parse(i),
                            Company=company[0],
                            Name=name[0],
                            Rank=int.Parse(rankinfo[1]),
                            Votes=int.Parse(rankinfo[2])
                        });
                        Console.WriteLine(content);
                        lock (locker)
                        {
                            if (File.Exists(file))
                            {
                                File.AppendAllText(file, content);
                            }
                            else
                                File.WriteAllText(file, content);
                        }
                    }
                    else
                    {
                        Console.WriteLine(string.Format("数据错误-{0}", i));
                    }
                }
                else
                {
                    Console.WriteLine(string.Format("无效ID-{0}", i));
                }
                
                p.Item2.Set();
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("异常退出-{0}",ex.Message));
                var p = (Tuple<string, EventWaitHandle>)o;
                p.Item2.Set();
            }
        }
        public static List<string> GetTop300()
        {
            var top = Environment.CurrentDirectory + "\\top300.txt";
            if (File.Exists(top))
                return File.ReadAllLines(top).ToList();
            return new List<string>();
        }
    }
}
